package cn.wolfcode.luowowo.mgrsite.listener;


import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.cache.service.IStrategyStatisVORedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.cache.vo.StrategyStatisVO;
import cn.wolfcode.luowowo.common.util.BeanUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * springBoot listener
 */

//@Component
public class RedisListener implements ApplicationListener<ContextRefreshedEvent> {
    @Reference
    private IStrategyDetailService strategyDetailService;

    @Reference
    private IStrategyStatisVORedisService strategyStatisVORedisService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("-----------------------初始化开始------------------------------");
        List<StrategyDetail> details = strategyDetailService.list();
        StrategyStatisVO vo = null;
        for (StrategyDetail detail : details) {

            //此时会出现一个问题,就是已经存在redis中的如果再次初始化会覆盖之前的,因此需要判断
            if (strategyStatisVORedisService.isRedisVOKey(detail.getId())){
                continue;
            }
            vo = new StrategyStatisVO();
            BeanUtil.copyProperties(vo,detail);

            vo.setDestId(detail.getDest().getId());
            vo.setDestName(detail.getDest().getName());
            vo.setStrategyId(detail.getId());
            strategyStatisVORedisService.setStrategyStatisVo(vo);
            System.out.println("-----------------------初始化结束------------------------------");
        }

        System.out.println("-----------------------hot初始化开始------------------------------");
        for (StrategyDetail detail : details) {
            if (strategyStatisVORedisService.isRedisVoExits(RedisKeys.STRATEGY_ZSET_SORT_HOT.getPreName(),detail.getId())){
                continue;
            }
            int score = detail.getViewnum()+detail.getReplynum();
            strategyStatisVORedisService.addHot(detail.getId(),score);
        }
        System.out.println("-----------------------hot初始化结束------------------------------");

        System.out.println("-----------------------国内外推荐初始化开始------------------------------");
        for (StrategyDetail detail : details) {
            if (strategyStatisVORedisService.isRedisVoExits(RedisKeys.STRATEGY_ZSET_SORT_COMMEND.getPreName(),detail.getId())){
                continue;
            }
            int score = detail.getThumbsupnum()+detail.getFavornum();
            strategyStatisVORedisService.addCommendScore(detail.getId(),score);
        }
        System.out.println("-----------------------国内外推荐初始化结束------------------------------");
    }
}
